# -*- coding:utf-8 -*-
import re
import pymysql
from lxml import etree
from selenium import webdriver
from tomorrow import threads


def image_update_main():
    # 和数据库建立连接
    conn = pymysql.connect('192.168.10.17', 'vne123', '123', charset='utf8')
    # 创建游标
    cur = conn.cursor()
    # 选择数据库
    cur.execute('use vnemy')
    ASIN_LIST = deal_with(cur=cur)
    print(ASIN_LIST)
    for asin in ASIN_LIST:
        try:
            get_response_data(ASIN=asin,cur=cur,conn=conn)
        except Exception as e:
            print(e)

def deal_with(cur):
    sql = """SELECT ASIN FROM tb_order_items WHERE GoodsImage = ''"""
    cur.execute(sql)
    sql_data = cur.fetchall()
    ASIN_LIST = list()
    for i in sql_data:
        ASIN_LIST.append(i[0])
    return ASIN_LIST


@threads(10)
def get_response_data(ASIN,cur,conn):
    # 2 爬取数据
    # data_of_list = []
    # print(ASIN)
    url = f"https://www.amazon.com/dp/{ASIN}"
    print(url)
    chrome_opt = webdriver.ChromeOptions()
    chrome_opt.add_argument("--headless")
    driver = webdriver.Chrome(chrome_options=chrome_opt)
    try:
        driver.get(url)
        # content = re.findall(r'"colorImages":(.*?),"heroImages"', driver.page_source)
        response = etree.HTML(driver.page_source)
        img = response.xpath("//div[@id = 'imgTagWrapperId']/img/@src")
        driver.close()
        if img:
            good_img = img[0]
            # print(good_img)
        else:
            good_img = "http://25562m1t29.wicp.vip:39304/dist/no_img.jpg"
    except:
        good_img = "http://25562m1t29.wicp.vip:39304/dist/no_img.jpg"
    # data_of_list.append({"ASIN":ASIN,"ImageUrl":good_img})
    i = {"ASIN":ASIN,"ImageUrl":good_img}
    sql = """UPDATE tb_order_items SET GoodsImage = '{}' WHERE ASIN = '{}'""".format(i['ImageUrl'], i['ASIN'])
    # print(sql)
    cur.execute(sql)
    conn.commit()
    print(ASIN+"已完成!")

if __name__ == '__main__':
    image_update_main()
    print("本次更新全部完成")
